/**
 * 多图预览
 * ivan 2013-12-16
 */

define(function(require, exports, module) {
    var $ = require('jquery');

    var defaults = {
        index: 0 // 当前索引
    }

    require('jquery/jquery.scrollbar');

    function Preview(options) {
        this.settings = $.extend({}, defaults, options);
        this.index = this.settings.index;
        this.w = 0;
        this.h = 0; // img 占位框
        this.src = ''; // 大图 src
        this.n = this.length; // 缩略图显示个数
    }

    Preview.prototype = {
    	constructor: Preview,
        init: function() {
            this.$layer = $('.image-multiple-preview').eq(0);
            this.$inner = this.$layer.children('.inner').eq(0);
            this.$picbox = this.$inner.children('.pic-box').eq(0);
            this.$img = $('#image_multiple_big');
            this.$loading = this.$img.siblings('.loading');
            this.$left = this.$img.siblings('.left').eq(0);
            this.$right = this.$left.next();
            this.$nav = $('#image_multiple_nav');
            this.$thumbsWrap = this.$nav.find('.pic-thumbs').eq(0);
            this.$thumbs = this.$thumbsWrap.children('li');
            this.$infobox = this.$inner.children('.info-box').eq(0);
            this.$infoboxInner = this.$infobox.children().eq(0);
            this.$scrollbox = this.$infoboxInner.children('.scrollbox').eq(0);
            this.length = this.$thumbs.length; // 缩略图的个数
            this.liOuterWidth = this.$thumbs.outerWidth(true);
            this.$prev = this.$nav.children('.prev').eq(0);
            this.$next = this.$prev.next();
            this.rw = 300; // 右边栏明确是这个宽度
            this.lvp = this.$picbox.outerHeight() - this.$picbox.height(); // img vertical padding
            this.lhp = this.$picbox.outerWidth() - this.$picbox.width(); // img box hr padding
            this.minw = 980; // .inner 最小宽度，取页面宽度
            this.minh = this.vp + 90; // .inner 最小高度，缩略图 90*90
            this.innerTop = 100; // hard code
            this.navPadding = parseInt(this.$nav.css('paddingLeft'), 10) + parseInt(this.$nav.css('paddingRight'), 10);

            $('body').css({
                'overflow': 'hidden'
            });

            this.size();

            if (this.length === 0) {
                throw new Error('缩略图的个数为 0');
            } else if (this.length > 1) {
                switch (this.index) {
                    case 0:
                        this.$right.show();
                        this.$next.show();
                        break;
                    case this.length - 1:
                        this.$left.show();
                        this.$prev.show();
                        break;
                    default:
                        this.$right.show();
                        this.$next.show();
                        this.$left.show();
                        this.$prev.show();
                }
            }

            var $active = this.$thumbs.eq(this.index);
            $active.addClass('active');
            // 加载大图
            this.loadImg($active.find('img')[0]);

            // 事件绑定
            var self = this;
            this.$layer.show()

            this.$infoboxInner.scrollbar({
                'content': '#image_preview_feed'
            });

            $(window).on('resize.preview', function(){
                setTimeout(function() {
                   self.size();
                   self.resizeImg();
               }, 200);
            });

            this.$layer.on('click', '.left, .prev', function(e) {
                e.preventDefault();
                self.to(self.index -1);
            }).on('click', '.right, .next', function(e) {
                e.preventDefault();
                self.to(self.index + 1);
            }).on('click', '.pic-item', function(e){
                var index = $(this).index();
                e.preventDefault();
                self.to(index);
            }).on('click', '.close', function(e) {
                e.preventDefault();
                self.close();
            });

            $(document).one('keydown', function(e) {
                if (e.which === 27) self.close();
            });
        },
        size: function() {
            var root = document.documentElement;
            var w = root.clientWidth;
            var h = root.clientHeight - this.innerTop;
            var innerWidth, innerHeight; //
            var left; //
            var lw; // 左栏宽度
            var rh;

            // width
            if (w <= this.minw) {
                innerWidth = this.minw;
                left = 10; // hard code
            } else {
                innerWidth = Math.floor(w*0.9);
                left = Math.floor(w*0.05)
            }
            lw = innerWidth - this.rw - this.lhp;
            this.w = lw;

            // height
            innerHeight = h <= this.minh ? this.minh : h;
            this.h = h - this.lvp;
            rh = innerHeight - 40;

            this.$inner.css({
            	'width': innerWidth,
                'left': left,
                'height': innerHeight
            });
            this.$picbox.css({
            	'width': lw,
                'height': this.h
            });
            this.$left.css({
                'top': Math.floor(this.h/2)
            });
            this.$right.css({
                'top': Math.floor(this.h/2)
            });
            this.$infobox.css({
            	'height': rh
            });

            // nav
            this.layoutNav();
        },
        resizeImg: function(w, h) {
            var newW = w;
            var newH = h;
            var n = 0; // margin-top 数值，实现垂直居中

            // this.w this.h 为 img 提供占位框
            if (w > this.w && h > this.h) {
                if (w >= h) {
                    newW = this.w;
                    newH = newW * (h/w);
                    if (newH > this.h) {
                        newH = this.h;
                        newW = newH * (w/h);
                    } else {
                        n = (this.h - newH)/2;
                    }
                } else {
                    newH = this.h;
                    newW = newH * (w/h);
                }
            } else if (w > this.w) {
                newW = this.w;
                newH = newW * (h/w);
                n = (this.h - newH)/2;
            } else if (h > this.h) {
                newH = this.h;
                newW = newH * (w/h);
            } else {
                n = (this.h - newH)/2;
            }

            this.$img.css({
                'width': Math.floor(newW) + 'px',
                'height': Math.floor(newH) + 'px',
                'marginTop': Math.floor(n) + 'px'
            });
        },
        layoutNav: function() {
            // TODO: 全部显示时是否不显示上下张按钮
            var w = this.length * this.liOuterWidth; // nav不要使用 margin
            if ( w > this.w) {
                this.n = Math.floor((this.w - this.navPadding)/this.liOuterWidth);
                w = this.n*this.liOuterWidth;
            }
            this.$nav.css({
                'width': w,
                'left': Math.floor((this.w - w - this.navPadding)/2)
            });
            this.$thumbsWrap.css({
                'width': this.length*this.liOuterWidth
            });
            this.leftNav();
        },
        leftNav: function() {
        	var left = 0;
        	if ( this.n < this.length) { // 有隐藏的项
        		if (this.index >= this.n) {
        			left = -(this.index - this.n + 1)*this.liOuterWidth;
        		}
        		this.$thumbsWrap.css('marginLeft', left);
            }
        },
        // 将大图的 src 放在小图的 data-src 上
        loadImg: function(thumb) {
            var self = this;
            var $thumb = $(thumb);
            var data = $thumb.data();
            var src = data.src; // 大图 src
            var w = h = 0;

            if (typeof src === 'undefined' || src.length === 0 ) {
                throw new Error("请检查缩略图的特性 data-src");
            }

            self.$img.hide();

            // 获取大图原始大小，并缓存起来
            if (data && data.size) {
                w = data.size.width;
                h = data.size.height;
                this.$img
            	.one('load', function() {
            		self.resizeImg(w, h);
            		self.$img.show();
            	})
            	.attr('src', src);
            } else {
            	self.$loading.show();
                var img = document.createElement('img');
                $(img).one('load', function() {
                	var w = this.width;
                	var h = this.height;
                	$thumb.data('size', {
                		'width': w,
                		'height': h
                	});
                	self.$img.one('load', function() {
                		self.resizeImg(w, h)
                		self.$loading.hide();
                		self.$img.show();
                	}).attr('src', src);
                }).attr('src', src);
            }
        },
        next: function() {
            if (this.index < this.length) {
                this.to(this.index + 1);
            }
        },
        prev: function() {
            if (this.index) {
                this.to(this.index - 1);
            }
        },
        to: function(index) {
            if (this.index === index) return;

            var $to = this.$thumbs.eq(index);
            this.$thumbs.eq(this.index).removeClass('active');
            $to.addClass('active');
            this.loadImg($to.find('img')[0]);
            this.index = index;
            this.leftNav();
            switch (index) {// 到达头尾时隐藏
                case 0:
                    this.$left.hide();
                    this.$prev.hide();
                    break;
                case this.length -1:
                    this.$right.hide();
                    this.$next.hide();
                    break;
                default:
                    this.$left.show();
                    this.$right.show();
                    this.$prev.show();
                    this.$next.show();
            }
        },
        close: function() {
            // this.$layer.hide();
            this.$layer.remove();
            $(window).off('.preview')
            $('body').css({
                'overflow': 'auto'
            });
        }
    }

    module.exports = Preview;

});
